/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package extension.phom.handler;

import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;
import extension.room.analyse.Card;
import extension.room.phom.PhomExtension;
import extension.room.phom.PhomGame;
import extension.room.phom.PhomPlayer;
import extension.room.phom.PhomResponse;
import java.util.List;
import log.Debug;

/**
 *
 * @author daz
 */
public class FightCardHandler extends BaseClientRequestHandler {

    @Override
    public void handleClientRequest(User user, ISFSObject params) {
        int cardFight = params.getInt(PhomFlag.CARD_SEND);
        logFightCard(cardFight, user.getName());
        PhomExtension tienlenExtension = (PhomExtension) getParentExtension();
        PhomGame game = tienlenExtension.getGame();
        PhomResponse response = tienlenExtension.getResponse();
        if (game.getIsPlay()) {
            PhomPlayer p = game.getPlayerFight();
            int canFight = checkCanFight(cardFight, p);
            if (canFight == 1) {
                game.removeCardInHand(cardFight);
                game.setCardFight(cardFight);
                if (p.getShowPhomOrder() == -1) {
                    p.generateListPhom();
                }
                List<User> listSend = tienlenExtension.getParentRoom().getUserList();
                listSend.remove(user);
                response.sendFightCard(cardFight, canFight, game.getGameTurn(), listSend);
                response.sendFightCard(cardFight, 0, canFight, game.getGameTurn(), p.getListPhom(), user);
                if (p.getListCardIds().isEmpty()) {
                    game.onFinishU(PhomGame.NOT_HAVE_PHOM);
                }
                game.nextTurn();
            } else {
                response.sendFightCard(canFight, p.getSeatPos(), user);
            }
        }
    }

    private void logFightCard(int fightCard, String name) {
        Debug.d(name + "- fight card :" + Card.getName(fightCard));

    }


    private int checkCanFight(int cardFight, PhomPlayer p) {
        if (!p.containCard(cardFight)) {
            return 0;
        }
        if (p.breakSet(cardFight)) {
            return 0;
        }
        return 1;
    }
}
